package com.ce.view;

import java.util.HashMap;
import java.util.Map;

import com.ce.activity.R;
import com.ce.activity.SoftApplication;
import com.ce.entity.VFlipperImg;
import com.ce.utils.AnimationUtils;
import com.ce.utils.AsyncImageLoader;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector.OnGestureListener;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.ViewFlipper;


public class VFlipperView extends LinearLayout {
	protected Map<String, VFlipperImg> mDatas;
	protected TextView mTextView;
	protected ViewFlipper mFlipper;
	protected LinearLayout mLyLogs;
	protected Context mContext;
	protected boolean mIsSupportMove;
	protected ScrollView mScrollView;
	
	public VFlipperView(Context context) {
		super(context);
		mContext = context;
		mIsSupportMove = true;
		initDatas(null);
	}
	
	public VFlipperView(Context context, AttributeSet attrs) {
		super(context, attrs);
		mContext = context;
		mIsSupportMove = true;
		initDatas(null);
	}

	public VFlipperView(Context context, Map<String, VFlipperImg> datas) {
		this(context, datas, true);
	}
	
	public VFlipperView(Context context, Map<String, VFlipperImg> datas, boolean isSupportMove) {
		super(context);
		this.mContext = context;
		mIsSupportMove = isSupportMove;
		initDatas(datas);
	}
	
	public void setParentView(ScrollView parentView) {
		this.mScrollView = parentView;
	}
	
	protected void initDatas(Map<String, VFlipperImg> datas) {
		setClickable(true);
		mDatas = new HashMap<String, VFlipperImg>();
		this.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
		LayoutInflater layoutInflater = LayoutInflater.from(mContext);
		View v = layoutInflater.inflate(R.layout.pub_vflipper, null);
		mFlipper = (ViewFlipper) v.findViewById(R.id.pub_vf);
		mTextView = (TextView) v.findViewById(R.id.pub_tv_img_title);
		mLyLogs = (LinearLayout) v.findViewById(R.id.pub_ly_img_logs);
		if(datas != null && !datas.isEmpty()) {
			mDatas.putAll(datas);
		}
		addView(v);
		refreshDatas();
		showCurrentInfo(mFlipper.getCurrentView());
	}
	
	protected void refreshDatas() {
		ImageView img = null;
		android.view.ViewGroup.LayoutParams imgParams = new android.view.ViewGroup.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
		LayoutParams logParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
		logParams.leftMargin = 20;
		VFlipperImg imgItem = null;
			for(String key : mDatas.keySet()) {
				imgItem = mDatas.get(key);
				img = new ImageView(mContext);
				img.setLayoutParams(imgParams);
				img.setScaleType(ScaleType.FIT_XY);
				img.setTag(key);
				setImageView(img, imgItem);
				mFlipper.addView(img);
				img = new ImageView(mContext);
				img.setTag(key);
				img.setLayoutParams(logParams);
				img.setImageResource(R.drawable.pic_viewflipper_off);
				mLyLogs.addView(img);
			}
	}
	
	protected void setImageView(ImageView imgView, VFlipperImg imgItem) {
		if(imgItem.getImgType() == 1) {
			imgView.setImageResource(imgItem.getImgResId());
		}else if(imgItem.getImgType() == 2) {
			imgView.setImageResource(R.drawable.pic_dish_default);
		}else if(imgItem.getImgType() == 3) {
			SoftApplication application = (SoftApplication) ((Activity)mContext).getApplication();
			AsyncImageLoader imgLoader = application.getImageLoader();
			Drawable drawable = imgLoader.loadDrawable(mContext, imgItem.getKey(), "imgicon", imgItem.getImgPath(), new AsyncImageLoader.ImageCallbackByKey() {
				@Override
				public void imageLoaded(Drawable imageDrawable, String urlPath, String key) {
					ImageView imgView = (ImageView) mFlipper.findViewWithTag(key);
					imgView.setImageDrawable(imageDrawable);
					startAnimation(imgView);
				}
			});
			if(drawable == null) {
				drawable = mContext.getResources().getDrawable(R.drawable.pic_dish_default);
			}
			imgView.setImageDrawable(drawable);
			startAnimation(imgView);
		}
	}
	
	protected void startAnimation(View v) {
		Animation animation = AnimationUtils.inAlphaAnimation(mContext);
		v.setAnimation(animation);
		animation.start();
	}
	
	protected void moveToLeft(){
		mFlipper.setInAnimation(AnimationUtils.inFromRightAnimation());
		mFlipper.setOutAnimation(AnimationUtils.outFromLeftAnimation());
		mFlipper.showNext();
		showCurrentInfo(mFlipper.getCurrentView());
	}
	
	protected void moveToRight() {
		mFlipper.setInAnimation(AnimationUtils.inFromLeftAnimation());
		mFlipper.setOutAnimation(AnimationUtils.outFromRightAnimation());
		mFlipper.showPrevious();
		showCurrentInfo(mFlipper.getCurrentView());
	}
	
	private void showCurrentInfo(View view) {
		if(view != null && view.getTag() != null) {
			Object obj = view.getTag();
			VFlipperImg item = mDatas.get(obj.toString());
			if(item != null) {
				mTextView.setText(item.getImgTitle());
				changeImgSource(mLyLogs.findViewWithTag(obj));
			}
		}
	}
	
	private void changeImgSource(View v) {
		int len = mLyLogs.getChildCount();
		ImageView imgView = null;
		for(int i = 0;  i <len; i++) {
			imgView = (ImageView) mLyLogs.getChildAt(i);
			if(imgView == v) {
				imgView.setImageResource(R.drawable.pic_viewflipper_on);
			}else{
				imgView.setImageResource(R.drawable.pic_viewflipper_off);
			}
		}
	}
	
	public OnGestureListener getOnGestureListener() {
		return mIsSupportMove ? new TouchGestureListener() : null;
	}
	
	protected Handler mHandler = new Handler () {
		public void handleMessage(android.os.Message msg) {
			if(((Activity) mContext).isFinishing()) {
				Log.d("DISH", "Activity is Finished!");
				return ;
			}
			if(msg.what == HANDLER_VFLIPPER_NEXT) {
				moveToLeft();
			}else if(msg.what == HANDLER_VFLIPPER_PREVIOUS) {
				moveToRight();
			}else if(msg.what == HANDLER_CLICK) {
				if(onClickListener != null) {
					VFlipperImg vFlipperImg = mDatas.get(msg.obj);
					onClickListener.onClickEvent(vFlipperImg);
				}
			}
		};
	};

	public void stop(){
		mIsFinshed = true;
		try{
			mThread.interrupt();
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	public void setLyLogVisible(int visibility) {
		if(mLyLogs != null) {
			mLyLogs.setVisibility(visibility);
		}
	}
	
	public void setTextViewVisible(int visibility) {
		if(mTextView != null) {
			mTextView.setVisibility(visibility);
		}
	}
	
	public void setIsSupportMove(boolean isSupportMove) {
		this.mIsSupportMove = isSupportMove;
	}
	
	public void start() {
		mIsFinshed = false;
		mFlipper.setDisplayedChild(0);
		mThread = new Thread(){
			public void run() {
				while(!mIsFinshed) {
					try{
						Thread.sleep(VFLIPPER_TIME) ;
						mHandler.sendEmptyMessage(HANDLER_VFLIPPER_NEXT);
					}catch(Exception e) {
						Log.d("DISH", e.toString());		
					}
				}
				mHandler.removeMessages(HANDLER_VFLIPPER_NEXT);
			};
		};
		mThread.start();
	}
	
	class TouchGestureListener extends SimpleOnGestureListener {
		@Override
		public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
				float velocityY) {
			if(Math.abs(velocityX) > VELOCITYX) {
				float distance = e1.getX() - e2.getX();
				if(Math.abs(distance) > MOVE_DISTANCE) {
					if(distance < 0) {
						mHandler.sendEmptyMessage(HANDLER_VFLIPPER_PREVIOUS);
					}else{
						mHandler.sendEmptyMessage(HANDLER_VFLIPPER_NEXT);
					}
					return true;
				}
			}
			return super.onFling(e1, e2, velocityX, velocityY);
		}
		@Override
		public boolean onSingleTapConfirmed(MotionEvent e) {
			if(isInView(e)) {
				mHandler.obtainMessage(HANDLER_CLICK, mFlipper.getCurrentView().getTag()).sendToTarget();
			}
			return super.onSingleTapConfirmed(e);
		}
	}

	public boolean isInView(MotionEvent e) {
		int y = (int) e.getY();
		int top = mScrollView == null ? 0 : mScrollView.getScrollY();
		return getBottom() - top > y;
	}
	
	public interface OnClickListener {
		void onClickEvent(VFlipperImg vFlipperImg);
	}
	
	protected  OnClickListener onClickListener;
	
	public void setOnClickListener(OnClickListener onClickListener) {
		this.onClickListener = onClickListener;
	}
	
	private Thread mThread ;
	protected boolean mIsFinshed;
	private final static int MOVE_DISTANCE = 60;
	private final static int VELOCITYX = 500;
	private final static int VFLIPPER_TIME = 5000;
	private final static int HANDLER_VFLIPPER_NEXT = 3;
	private final static int HANDLER_VFLIPPER_PREVIOUS = 4;
	private final static int HANDLER_CLICK = 5;
}
